package com.kl.simple;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.junit.Test;

import java.io.*;

public class SimpleTest {

    /**
     * 将一个简单对象序列化为XML数据
     */
    @Test
    public void test1() throws JsonProcessingException {
        XmlMapper xmlMapper = new XmlMapper();
        String xml = xmlMapper.writeValueAsString(new SimpleBean());
        /*
         * <SimpleBean>
         *     <x>1</x>
         *     <y>2</y>
         * </SimpleBean>
         */
        System.out.println(xml);
        assertNotNull(xml);
    }

    /**
     * 将一个简单对象序列化为xml格式数据并存储到指定路径下
     */
    @Test
    public void test2() throws IOException {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.writeValue(new File("src/main/java/com/kl/simple/simple_bean.xml"), new SimpleBean());
        File file = new File("simple_bean.xml");
        assertNotNull(file);
    }

    /**
     * 将简单xml格式的数据反序列化为简单对象
     */
    @Test
    public void test3() throws IOException {
        XmlMapper xmlMapper = new XmlMapper();
        String xmlContent = "<SimpleBean>\n" +
                "    <x>1</x>\n" +
                "    <y>2</y>\n" +
                "</SimpleBean>";
        SimpleBean value
                = xmlMapper.readValue(xmlContent, SimpleBean.class);
        System.out.println(value);
    }

    /**
     * 从xml文件反序列化
     */
    @Test
    public void test4() throws IOException {
        File file = new File("src/main/java/com/kl/simple/simple_bean.xml");
        XmlMapper xmlMapper = new XmlMapper();
        String xml = inputStreamToString(new FileInputStream(file));
        SimpleBean value = xmlMapper.readValue(xml, SimpleBean.class);
        System.out.println(value);
    }

    public String inputStreamToString(InputStream is) throws IOException {
        StringBuilder sb = new StringBuilder();
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

    private void assertNotNull(Object xml) {
        if (xml == null) {
            throw new NullPointerException("序列号失败");
        }
    }

}
